package com.sjb.sixteen_journey_backend.utils.ws;

import com.alibaba.fastjson.JSON;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.config.GetHttpSessionConfig;
import com.sjb.sixteen_journey_backend.entity.ChatList;
import com.sjb.sixteen_journey_backend.entity.User;
import com.sjb.sixteen_journey_backend.mapper.UserMapper;
import com.sjb.sixteen_journey_backend.service.IChatListService;
import com.sjb.sixteen_journey_backend.service.IUserService;
import com.sjb.sixteen_journey_backend.utils.MessageUtils;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import com.sjb.sixteen_journey_backend.utils.ws.pojo.Message;
import com.sjb.sixteen_journey_backend.utils.ws.pojo.SocketMsg;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version v1.0
 * @ClassName: ChatEndpoint
 * @Description: TODO(一句话描述该类的功能)
 * @Author: 黑马程序员
 */
//@ServerEndpoint(value = "/chat/{userName}",configurator = GetHttpSessionConfig.class)
@ServerEndpoint(value = "/singleChat/{userName}")
//@ServerEndpoint(value = "/chat")
@Component
@Slf4j
public class ChatEndpoint implements InitializingBean {

    @Autowired
    private IUserService userService;
    static  IUserService staticUserService;

    @Autowired
    private IChatListService chatListService;

    static  IChatListService staticIChatListService;

    /**
     * 存放Session集合，方便推送消息 （jakarta.websocket）
     */
    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();




    /**
     * 建立websocket连接后，被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        //1，将session进行保存
//        onlineUsers.put(session.getId(),session);
        onlineUsers.put(userName,session);
        Session session1 = onlineUsers.get(userName);
        log.info("[onOpen] 新建连接 session："+session.getId()+"连接成功" +"当前连接人数："+onlineUsers.size());
        //2，广播消息。需要将登陆的所有的用户推送给所有的用户
//        String message = MessageUtils.getMessage(true,null,getFriends());
//        broadcastAllUsers(message);
    }

    public Set getFriends() {
        Set<String> set = onlineUsers.keySet();
        return set;
    }

    private void broadcastAllUsers(String message) {
        try {
            //遍历map集合
//            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
//            for (Map.Entry<String, Session> entry : entries) {
            for (Session session : onlineUsers.values()) {
                //获取到所有用户对应的session对象
//                Session session = entry.getValue();
                //发送消息
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            //记录日志
            throw new RuntimeException(e);
        }
    }

    /**
     * 浏览器发送消息到服务端，该方法被调用
     *
     * 张三  -->  李四
     * @param message*/

    @OnMessage
    public void onMessage(String message) {
        try {
            log.info("[onMessage] 服务端接受消息："+message);
            ChatList chatList = JSON.parseObject(message, ChatList.class);
            User fromUser = staticUserService.getUserById(chatList.getFromUserId());
            User toUser = staticUserService.getUserById(chatList.getToUserId());
            chatList.setFromAvatar(fromUser.getAvatar());
            chatList.setFromName(fromUser.getUsername());
            chatList.setToAvatar(toUser.getAvatar());
            chatList.setToName(toUser.getUsername());
            staticIChatListService.save(chatList);

            String json = JSON.toJSONString(chatList);
            Session fromSession=onlineUsers.get(chatList.getFromName());
            fromSession.getBasicRemote().sendText(json);
            Session toSession=onlineUsers.get(chatList.getToName());
            if(toSession!=null){
                toSession.getBasicRemote().sendText(json);
            }


        } catch (Exception e) {
            //记录日志
            throw new RuntimeException(e);
        }
    }

    /**
     * 断开 websocket 连接时被调用
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        onlineUsers.remove(session.getId());
        log.info("[onClose] 断开连接 session："+session.getId()+"连接成功" +"当前连接人数："+onlineUsers.size());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("[onError] session："+session.getId()+"连接异常" +"当前连接人数："+onlineUsers.size());
    }

    @Override
    public  void afterPropertiesSet() throws Exception {
        staticUserService = userService;
        staticIChatListService = chatListService;
    }
}
